package com.example.demo.controller;

import com.example.demo.Utils.TimeUtils;
import com.example.demo.bean.Caculater;
import com.example.demo.bean.ResultVO;
import com.example.demo.config.Variable;
import com.example.demo.mapper.CaculateMapper;
import com.example.demo.service.CaculateService;
import com.example.demo.service.impl.OrdersServiceImpl;
import io.swagger.annotations.Api;
import org.apache.poi.ss.formula.functions.Count;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

@Api
@RequestMapping("api/caculater")
@RestController
@CrossOrigin
public class CaculaterController {
    @Autowired
    CaculateService caculateService;

    @Autowired
    CaculateMapper caculateMapper;

    @Autowired
    public OrdersServiceImpl ordersService;
    /**
     * 返回统计结果
     * @return
     */
    @GetMapping("statistical")
    public ResultVO Caculater(String year,String month,String date){
//        caculateService.getMomeySumByDate();
        return ResultVO.success("请求成功");

    }

    /**
     * 返回预警结果
     * @return
     */
    @GetMapping("warning")
    public ResultVO add(){
        return ResultVO.success("请求成功");
    }

    /**
     * 新增一条本周采购总额数据
     * @return
     */
    @PostMapping("addMoney")
    public ResultVO addMoney(){
        boolean hadAdd = caculateService.hadAddBuySum();
        //近一周内没有统计数据，才生成一条统计数据
        float sumMoney = caculateMapper.caculateSumMoney();
        if (sumMoney >Variable.CountBudgetMoney){
            return ResultVO.error("剩余预算不足，请联系酸奶负责人添加预算");
        }

        List<String> unSelectedDrinkList = caculateMapper.selectUnselectDrinkName();

        if (unSelectedDrinkList .size() != 0){
            return ResultVO.error(unSelectedDrinkList+"未选饮料");
        }else {
            if (!hadAdd){caculateService.addBuySum();}
            return ResultVO.success("请求成功");
        }

    }

    /**
     * 查询某年的总额和某年中每月的情况
     * param示例 2021
     * @return示例 {"yearSum":1582.0,"monthMoney":[{"money":1466.0,"date":"08"},{"money":116.0,"date":"09"}]}}
     */
    @GetMapping("year")
    public ResultVO queryMoneyOfYearAndMonth(String year){
        Map sumOfYearAndMonth = caculateService.queryMoneyOfYear(year);
        return ResultVO.success(sumOfYearAndMonth);
    }

    /**
     * 查询某个月的每一次的采购情况
     * param示例 2021,08
     * @return示例 [{"money":103.0,"date":"15"},{"money":106.0,"date":"15"}]
     */
    @GetMapping("month")
    public ResultVO queryEveryTimesSumOfMonth(String date,String month){
        Map<String,Float> monthMoney = new TreeMap<>();
        monthMoney.put("01", 0f);
        monthMoney.put("02",0f);
        monthMoney.put("03",0f);
        monthMoney.put("04",0f);
        monthMoney.put("05",0f);
        monthMoney.put("06",0f);
        monthMoney.put("07",0f);
        monthMoney.put("08",0f);
        monthMoney.put("09",0f);
        monthMoney.put("10",0f);
        monthMoney.put("11",0f);
        monthMoney.put("12",0f);

        String[] dateArr = date.split("-");
        String year = dateArr[0];
        List axis = new ArrayList<String>();

        Map result = new HashMap();
        List<Caculater> everyTimeSum = new ArrayList();
        List yAxis =new ArrayList();
        float yearMomey = caculateMapper.queryMoneyOfYear(year);
        if ("0".equals(month)){
            List<Caculater> moneyOfEachMonth = caculateMapper.queryMoneyOfMonth(year);
            for (Caculater monthcaculater:moneyOfEachMonth) {
                monthMoney.put(monthcaculater.getDate().substring(5),monthcaculater.getMoney());
            }
            axis.add("01月");
            axis.add("02月");
            axis.add("03月");
            axis.add("04月");
            axis.add("05月");
            axis.add("06月");
            axis.add("07月");
            axis.add("08月");
            axis.add("09月");
            axis.add("10月");
            axis.add("11月");
            axis.add("12月");
            yAxis =monthMoney.values().stream().collect(Collectors.toList());
        }else {

            List<Caculater> axi = caculateService.queryEveryTimesOfMonth(Integer.valueOf(year),Integer.valueOf(month));

            for (Caculater caculater: axi) {
                yAxis.add(caculater.getMoney());
                axis.add(caculater.getDate()+"号");
            }
        }
        result.put("yAxis",yAxis);
        result.put("xAxis",axis);
        result.put("yearMomey",yearMomey);
        return ResultVO.success(result);
    }

    @GetMapping("budget")
    public ResultVO caculateBuget() {

        //本月已花费
        float thismonthCost =  caculateMapper.queryThisMonthCost(TimeUtils.getNowTime().toString().substring(0,7));
        //本月剩余预算
        float balance = Variable.thisMonthBudge - thismonthCost;


        String nowDay = TimeUtils.getNowTime().toString().substring(8,10);
        Integer thisMonthBalance = (30-Integer.valueOf(nowDay))/7;

        //人均预算
        float peopleCount = ordersService.queryPeopleCount();
        float personBudget = (Variable.thisMonthBudge/thisMonthBalance/peopleCount);

        Map result = new HashMap();
        result.put("budget",Variable.thisMonthBudge);
        result.put("cost",thismonthCost);
        result.put("balance",balance);
        result.put("personBudget",personBudget);
        result.put("message","当前总预算"+Variable.CountBudgetMoney+"将使用"+Variable.times+"周");
        return ResultVO.success(result);
    }

    @GetMapping("updateBuget")
    public ResultVO caculateBuget(float money,String date ) {
        String nowTime = TimeUtils.getNowTime().toString();
        //相差了多少天
        int differentDays = differentDays(new Date(Integer.parseInt(nowTime.substring(0,4)),Integer.parseInt(nowTime.substring(5,7)),Integer.parseInt(nowTime.substring(8,10))),
                new Date(Integer.parseInt(date.substring(0,4)),Integer.parseInt(date.substring(5,7)),Integer.parseInt(date.substring(8,10))));
        //相差了多少周
        int differentWeek = differentDays/7;
        if (differentWeek != 0){
            Variable.times = differentWeek;
        }
        //当前总预算
        Variable.CountBudgetMoney += money;
        //如果月份变量不等于当前月，则更新本月预算
        String thisMonth = TimeUtils.getNowTime().toString().substring(5,7);
        //本月剩余天数
        String nowDay = TimeUtils.getNowTime().toString().substring(8,10);
        Integer thisMonthBalance = (30-Integer.valueOf(nowDay))/7;
        if (!thisMonth.equals(Variable.month)){
            //当前月的预算
            Variable.thisMonthBudge = (Variable.CountBudgetMoney/Variable.times)*thisMonthBalance;
            Variable.month = thisMonth;
        }

        //本月已花费
        float thismonthCost =  caculateMapper.queryThisMonthCost(TimeUtils.getNowTime().toString().substring(0,7));
        //本月剩余预算
        float balance = Variable.thisMonthBudge - thismonthCost;
        //人均预算
        float peopleCount = ordersService.queryPeopleCount();
        float personBudget = Variable.CountBudgetMoney/(Variable.times*peopleCount);

        Map result = new HashMap();
        result.put("budget",Variable.thisMonthBudge);
        result.put("cost",thismonthCost);
        result.put("balance",balance);
        result.put("personBudget",personBudget);
        result.put("message","当前总预算"+Variable.CountBudgetMoney+"将使用"+Variable.times+"周");

        return ResultVO.success(result);
    }


    public static int differentDays(Date date1,Date date2)
    {
        Calendar cal1 = Calendar.getInstance();
        cal1.setTime(date1);

        Calendar cal2 = Calendar.getInstance();
        cal2.setTime(date2);
        int day1= cal1.get(Calendar.DAY_OF_YEAR);
        int day2 = cal2.get(Calendar.DAY_OF_YEAR);

        int year1 = cal1.get(Calendar.YEAR);
        int year2 = cal2.get(Calendar.YEAR);
        if(year1 != year2) //同一年
        {
            int timeDistance = 0 ;
            for(int i = year1 ; i < year2 ; i ++)
            {
                if(i%4==0 && i%100!=0 || i%400==0) //闰年
                {
                    timeDistance += 366;
                }
                else //不是闰年
                {
                    timeDistance += 365;
                }
            }

            return timeDistance + (day2-day1) ;
        }
        else //不同年
        {
            return day2-day1;
        }
    }



}
